<template>
  <ul>
    <li
      v-for="(item, index) in bzs"
      :key="item.id"
      @click="openChildren(item, index)"
      :class="['pli', activeIndex === index ? 'active' : '']"
    >
      <img :src="activeIndex === index ? item.aicon : item.icon" alt="" />
      <span>{{ item.title }}</span>
      <template v-if="item.children">
        <div class="er" :style="{ top: index * 30 + 'px' }" v-show="activeIndex == index">
          <ul>
            <li v-for="it in item.children" :key="it.id" @click="todialog(it)">
              <span>{{ it.title }}</span></li
            >
          </ul>
        </div>
      </template>
    </li>
  </ul>
  <plottingDialog
    :title="title"
    :nowentity="oldMark"
    @close="closeEntity"
    v-if="point"
    @update-entity="updateEntity"
    :key="toolChildrenId"
  />
  <lineDialog
    :key="toolChildrenId"
    :nowentity="oldMark"
    :title="title"
    :toolChildrenId="toolChildrenId"
    @close="closeEntity"
    v-if="line"
    @update-entity="updateEntity"
  />
  <areaDialog
    :key="toolChildrenId"
    :nowentity="oldMark"
    :title="title"
    :toolChildrenId="toolChildrenId"
    @close="closeEntity"
    v-if="area"
    @update-entity="updateEntity"
  />
  <textDialog
    :key="toolChildrenId"
    :nowentity="oldMark"
    :title="title"
    @close="closeEntity"
    v-if="text"
    @update-entity="updateEntity"
  />

  <teleport to="body">
    <div class="pt" style="position: fixed; top: 10vh; right: 20vw">
      <roomDialog
        :dialogVisible="pointFlag"
        @close="exitPoint"
        size="small"
        title="输入经纬度创建坐标点"
        v-if="pointFlag"
      >
        <div style="display: flex; justify-content: space-between; margin-top: 30px">
          <darkInput v-model="lon" placeholder="输入经度" title="经度" style="width: 200px" />
          <darkInput v-model="lat" placeholder="输入纬度" title="纬度" style="width: 200px" />
        </div>
        <div style="margin-top: 30px">
          <el-button align="right" type="primary" style="float: left" @click="toPoint"
            >坐标定位</el-button
          >
          <el-button
            align="right"
            type="primary"
            style="float: right; margin-left: 20px"
            @click="addPoint"
            >创建点标注</el-button
          >
          <el-button align="right" style="float: right" @click="exitPoint">取消</el-button>
        </div>
      </roomDialog>
    </div>
  </teleport>
   <teleport to="body">
  <screenDialog
    :dialogVisible="exportAll"
    @close="exitExport"
    size="small"
    title="Excel数据导入"
    v-if="exportAll"
  >
    <div
      style="display: flex; justify-content: space-between; margin-top: 30px; align-items: center"
    >
      <darkInput
        v-model="filename"
        placeholder="选择要导入的Excel文件"
        :readonly="true"
        style="width: 300px"
      />

      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="#"
        :auto-upload="false"
        accept=".xls,.xlsx"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="handleChange"
      >
        <template #trigger>
          <el-button type="primary">上传文件</el-button>
        </template>
      </el-upload>
    </div>
    <div style="margin-top: 30px">
      <el-button align="right" type="primary" style="float: left" @click="downExcel"
        >下载Excel模版</el-button
      >
      <el-button
        align="right"
        type="primary"
        style="float: right; margin-left: 20px"
        @click="handleFileUpload"
        >导入</el-button
      >
      <el-button align="right" style="float: right" @click="exitExport">退出</el-button>
    </div>
  </screenDialog>
   </teleport>
</template>

<script setup>
import { ref } from 'vue'
import { options_mark } from '../../../js/test'
import plottingDialog from './other/plottingDialog.vue'
import lineDialog from './other/lineDialog.vue'
import areaDialog from './other/areaDialog.vue'
import textDialog from './other/textDialog.vue'
import { genFileId } from 'element-plus'
import * as XLSX from 'xlsx'
import { addSysmMapMark } from '../../../../api/sysmapmark'
import { useMapStoreStore } from '../../../../stores/index'
import { createPointAndToView } from '../../../../api/gis3d/maputils'

const store = useMapStoreStore()
const point = ref(false)
const line = ref(false)
const area = ref(false)
const text = ref(false)
const activeIndex = ref(-1)
const pointFlag = ref(false)
const title = ref('')
const lon = ref('')
const lat = ref('')
const bzs = [
  {
    id: 1,
    title: '点标注',
    icon: '/static/assets/3d/dian.png',
    aicon: '/static/assets/3d/dian-a.png',
    children: [
      {
        id: 2,
        title: '点击定位',
        cb: options_mark.点击定位
      },
      {
        id: 3,
        title: '坐标定位',
        cb: createPoint
      },
      {
        id: 4,
        title: '批量导入',
        cb: exportAllPoint
      }
    ]
  },
  {
    id: 5,
    title: '线标注',
    icon: '/static/assets/3d/xian.png',
    aicon: '/static/assets/3d/xian-a.png',
    children: [
      {
        id: 6,
        title: '折线',
        cb: options_mark.线
      },
      {
        id: 7,
        title: '圆形线',
        cb: () => {
          options_mark.圆(0)
        }
      },
      {
        id: 8,
        title: '矩形线',
        cb: () => {
          options_mark.矩形(0.0001)
        }
      }
    ]
  },
  {
    id: 9,
    title: '面标注',
    icon: '/static/assets/3d/mian.png',
    aicon: '/static/assets/3d/mian-a.png',
    children: [
      {
        id: 10,
        title: '自由面',
        cb: options_mark.多边形
      },
      {
        id: 11,
        title: '圆形面',
        cb: () => {
          options_mark.圆(0.5)
        }
      },
      {
        id: 12,
        title: '矩形面',
        cb: () => {
          options_mark.矩形(0.5)
        }
      },
      {
        id: 13,
        title: '细直箭头',
        cb: options_mark.细直箭头
      },
      {
        id: 14,
        title: '直箭头',
        cb: options_mark.直箭头
      },
      {
        id: 14,
        title: '弯箭头',
        cb: options_mark.弯箭头
      }
    ]
  },
  {
    id: 15,
    title: '文字标注',
    icon: '/static/assets/3d/wz.png',
    aicon: '/static/assets/3d/wz-a.png',
    cb: options_mark.文字标注
  }
]

const openChildren = (item, index) => {
  if (item.id === 15) {
    closeEntity()
    nowItem = item
    title.value = item.title
    text.value = true
    item.cb && item.cb()
  }
  activeIndex.value = index
}
const toolChildrenId = ref(-1)
var oldMark = ref(null)
let nowItem = null
const todialog = (item) => {
  nowItem = item
  closeEntity()
  item.cb && item.cb()
}

const showDialog = (item) => {
  title.value = item.title
  toolChildrenId.value = item.id
  if (item.id === 6 || item.id === 7 || item.id === 8) {
    line.value = true
    point.value = false
    area.value = false
    text.value = false
  }
  if (item.id === 2) {
    point.value = true
    line.value = false
    area.value = false
    text.value = false
  }
  if (item.id >= 10 && item.id < 15) {
    area.value = true
    point.value = false
    line.value = false
    text.value = false
  }
  if (item.id === 15) {
    text.value = true
    area.value = false
    point.value = false
    line.value = false
  }
}

const closeEntity = () => {
  point.value = false
  line.value = false
  area.value = false
  text.value = false
  oldMark.value && oldMark.value.destroy()
  var arr = map3d.getAllMarks()
  for (const element of arr) {
    if (element.options.attr.marktype !== 'mark-poi') {
      element.destroy()
    }
  }
}

function getMarkDataInfo(item) {
  if (item.options.attr.marktype == 'mark-poi') {
    return
  }
  oldMark.value = item
  showDialog(nowItem)
}

onMounted(() => {
  viewEvent.on('nowMarkItem', getMarkDataInfo)
})
onUnmounted(() => {
  viewEvent.off('nowMarkItem', getMarkDataInfo)
})

function createPoint() {
  pointFlag.value = !pointFlag.value
}

var isPoint = false
const toPoint = () => {
  let a = lon.value == "" ? "" :Number(lon.value)
  let b = lat.value == "" ? "" :Number(lat.value)
  if (a === '' || b === '' || a > 180 || a < -180 || b > 90 || b < -90) {
    ElMessage({
      message: '请输入经纬度,经度180 -180 纬度 90 -90',
      type: 'warning'
    })
    return
  }
  oldMark.value && oldMark.value.destroy()
  title.value = '坐标定位'
  // point.value = true
  // map3d.inputtMark(a, b)
  var pointJson = {
    type: 'Feature',
    properties: {
      id: '',
      type: 'billboard',
      style: {
        scale: 1,
        image: '/static/icon/poi.png',
        horizontalOrigin: 0,
        verticalOrigin: 1,
        label: {
          font_size: 26,
          color: '#ffffff',
          outline: true,
          outlineColor: '#000000',
          pixelOffsetY: -60
        }
      }
    },
    geometry: { type: 'Point', coordinates: [a, b, 0] }
  }
  // pointJson.properties.marktype = 'mark-poi'
  // pointJson.properties.marktypes = '点'
  map3d.drawMarkBydata(JSON.stringify(pointJson))
  var entits = map3d.getAllMarks()
  oldMark.value = entits[entits.length - 1]
  isPoint = true
  map3d.cameraMoveTo({
    lat: b,
    lng: a,
    alt: 300000,
    heading: 350,
    pitch: -90
  })
}
const addPoint = () => {
  let a = lon.value
  let b = lat.value
  if (a === '' || b === '' || a > 180 || a < -180 || b > 90 || b < -90) {
    ElMessage({
      message: '请输入经纬度,经度180 -180 纬度 90 -90',
      type: 'warning'
    })
    return
  }
  point.value = true
  if (!isPoint) {
    toPoint(true)
  }
   pointFlag.value = false;
    lon.value = '';
    lat.value = '';
  // exitPoint()
}

const updateEntity = (image) => {
  if (image == '') {
    map3d.clearMarks()
    return
  }
  if (image === 'del') {
    exitPoint(true)
  }
}

const exitPoint = (f) => {
  lon.value = ''
  lat.value = ''
  oldMark.value && oldMark.value.destroy()
  pointFlag.value = false
}

const exportAll = ref(false)
const filename = ref('')
const uploadRef = ref()
let fileBuffer = null

const handleExceed = (files) => {
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value.handleStart(file)
}
const handleChange = (file) => {
  fileBuffer = file.raw
  filename.value = file.name
}

function exportAllPoint() {
  exportAll.value = !exportAll.value
}

const handleFileSelected = (e) => {
  filename.value = e.name
}

const exitExport = () => {
  exportAll.value = false
  filename.value = ''
}

const downExcel = () => {
  let link = document.createElement('a')
  link.href = '/static/file/点坐标导入模板.xlsx'
  link.download = `点坐标导入模板.xlsx`
  link.click()
}

const handleFileUpload = () => {
  const file = fileBuffer
  const reader = new FileReader()
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    // 获取第一个工作表
    const worksheet = workbook.Sheets[workbook.SheetNames[0]]
  
    // 将工作表数据转换为 JSON 格式
    const jsonData = XLSX.utils.sheet_to_json(worksheet)

    var newData = []
    for (const e of jsonData) {
      if (!e['编号'] || isNaN(e['编号']) ||e['编号'] == '' ) {
        // alert('编号只能为数字')
        // return
        break;
      }
      newData.push(e)
    }
    submitUpload(newData)
  }
  reader.readAsArrayBuffer(file)
}

const submitUpload = (json) => {
      const idSet = new Set()
    for (const e of json) {
      if (idSet.has(e['编号'])) {
        return alert('编号只能唯一'  +"----------编号:"+ e['编号'])
      }
      if (
      !e['标注名称'] ||
      !e['经度'] ||
      !e['纬度'] ||
      e['标注名称'] === '' ||
      e['经度'] === '' ||
      e['纬度'] === ''
    ) {
      return alert('标注名称,经度，纬度 不能为空' +"----------编号:"+e['编号'])
    }
      idSet.add(e['编号'])
    }
    let jindex = 0;
  for (const item of json) {

    let mstyle =
      item['样式'] == '' || item['样式'] == '默认'
        ? { img: '/static/icon/poi.png' }
        : { img: `/static/assets/3d/icon/${item['样式']}.png` }

    let pointStr = {
      type: 'Feature',
      properties: {
        id: '',
        type: 'billboard',
        style: {
          scale: 1,
          image: mstyle.img,
          horizontalOrigin: 0,
          verticalOrigin: 1,
          label: {
            font_size: 26,
            color: '#ffffff',
            outline: true,
            outlineColor: '#000000',
            pixelOffsetY: -60
          }
        }
      },
      geometry: { type: 'Point', coordinates: [Number(item['经度']), Number(item['纬度']), 0] }
    }

    pointStr.properties.marktype = 'mark-poi'
    pointStr.properties.marktypes = '点'
    let formData = new FormData()
    formData.append('markName', item['标注名称'])
    formData.append('markMemo', item['描述'] || '')
    formData.append('markType', '点')
    formData.append('markStyle', JSON.stringify(mstyle))
    formData.append('markExt', JSON.stringify(pointStr))
    formData.append('earthquakeId', store.eqid)

    addSysmMapMark(formData).then((e) => {
    jindex++;
      ElMessage({
        message: '上传成功',
        type: 'success',
        plain: true
      })
      
      exportAll.value = false;
      if(jindex == json.length){
      store.markFlag = !store.markFlag
      }
    })
  }
}
</script>

<style lang="scss" scoped>
ul,
li {
  padding: 0;
  margin: 0;
}
:deep(.el-upload-list) {
  display: none;
}

.pli {
  height: 60px;
  list-style: none;
  line-height: 60px;
  display: flex;
  align-items: center;
  padding-left: 10px;
  color: #b9eeff;

  img {
    width: 22px;
    height: 22px;
    object-fit: contain;
    margin-right: 30px;
  }

  cursor: pointer;
}

.pli:hover,
.active {
  background: #051420;
  color: #0e9cff;
}

.er {
  position: absolute;
  width: 140px;
  min-height: 70px;
  top: 32px;
  left: -145px;

  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);

  li {
    display: flex;
    justify-content: center;
    color: #b9eeff;

    &:hover {
      background: #051420;
      color: #0e9cff;
    }
  }
}
</style>
